﻿using System;
using BestHTTP;
using BestHTTP.Logger;
using UnityEngine;

namespace Networking.Runtime
{
    public class DownLoadSpeedWatcher
    {
        public static readonly DownLoadSpeedWatcher SpeedWatcher = new DownLoadSpeedWatcher();

        public TimeSpan WATCHER_INTERVAL_TIME = new TimeSpan(0,0,2);
        private long DownLoadSize { get;  set; }
        private DateTime _startRecordTime;
        private bool _isInit = false;
        public double DownLoadSpeed { get; private set; }

        private DownLoadSpeedWatcher()
        {
            Application.runInBackground = true;
            HTTPUpdateDelegator.IsThreaded = true;
            HTTPManager.Logger.Level = Loglevels.Error;
            HTTPManager.IsCachingDisabled = true;
            HTTPManager.RequestTimeout = TimeSpan.FromSeconds(DownLoadSetting.DOWNLOAD_TIME_OUT);
            HTTPManager.ConnectTimeout = TimeSpan.FromSeconds(DownLoadSetting.CONNECT_TIMEOUT);
            HTTPManager.Setup();
        }

        public double GetSpeed()
        {
            Init();
            if (DateTime.Now.Subtract(_startRecordTime) >= WATCHER_INTERVAL_TIME)
            {
                double seconds = DateTime.Now.Subtract(_startRecordTime).TotalSeconds;
                DownLoadSpeed = DownLoadSize /seconds;
                _startRecordTime = DateTime.Now;
                DownLoadSize = 0;
            }
            return DownLoadSpeed;
        }

        private void Init()
        {
            if (!_isInit)
            {
                _startRecordTime = DateTime.Now;
                _isInit = true;
                DownLoadSpeed = 0;
                DownLoadSize = 0;
            }
        }
        
        public void RecordLoadSize(long size)
        {
            Init();
            if (DateTime.Now.Subtract(_startRecordTime) < WATCHER_INTERVAL_TIME)
            {
                DownLoadSize += size;
            }
            else
            {
                _startRecordTime = DateTime.Now;
                DownLoadSize = 0;
            }
        }
    }
}